package com.haoshui.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haoshui.domain.entity.ArticleTag;
import com.haoshui.mapper.ArticleTagMapper;
import com.haoshui.service.ArticleTagService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 文章标签关联表(ArticleTag)表服务实现类
 *
 * @author makejava
 * @since 2022-10-03 11:31:24
 */
@Service("articleTagService")
public class ArticleTagServiceImpl extends ServiceImpl<ArticleTagMapper, ArticleTag> implements ArticleTagService {

    @Override
    public List<Long> getTagIdsByArticleId(Long id) {
        //查出所有articleId = id 的ArticleTag
        LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleTag::getArticleId, id);
        List<ArticleTag> list = list(queryWrapper);

        //取出ArticleTag中的tagId
        List<Long> collect = list.stream()
                .map(articleTag -> articleTag.getTagId())
                .collect(Collectors.toList());

        return collect;
    }

    @Override
    public boolean updateTags(Long articleId, List<String> tags) {
        //删除全部articelId为目标的记录
        LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleTag::getArticleId, articleId);
        //TODO 如果删除失败，需要处理
        remove(queryWrapper);

        //把String 转成 ArticleTag
        List<ArticleTag> collect = tags.stream()
                .map(tag -> new ArticleTag(articleId, Long.valueOf(tag)))
                .collect(Collectors.toList());


        //插入新的数据
        boolean b = saveBatch(collect);

        return b;
    }


}
